package com.techysky.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.util.FileCopyUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.techysky.entity.MultiMedia;
import com.techysky.repository.MultiMediaRepository;

/**
 * IETM上传工具类
 * @author nichao
 *
 */
public class IetmFileUtils implements Serializable{

	private static final String INFO_ENTITY_IDENT = "infoEntityIdent";
	private static final String GRAPHIC = "graphic";
	private static final String TITLE2 = "title";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;  
	private static final Log log=LogFactory.getLog(IetmFileUtils.class);
	private IetmFileUtils(){
		
	}
	/**
	 * 方法功能:图片上传
	 * @param file
	 * @param request
	 * @param model
	 * @return 
	 * @author nichao
	 */
	public static void uploadImage(String imageName,String imagePath) {  	 	

		 	String fileName=imageName;
			int unixSep = fileName.lastIndexOf('/');
			int winSep = fileName.lastIndexOf('\\');
			int pos = winSep > unixSep ? winSep : unixSep;
			if (pos != -1)  {
				fileName=fileName.substring(pos + 1);
			}
		 	File file = new File(imageName);
		 	if(null!=file.getName()&&!"".equals(file.getName())){
	        File targetFile = new File(imagePath);  
	        if(!targetFile.exists()){  
	            targetFile.mkdirs();
	        }  
	        //保存  
	        try {  
	            FileCopyUtils.copy(file, new File(imagePath+"/"+fileName));
	        } catch (Exception e) {
	        	log.info(e);
		 	}
	    }
	 }
	public static void  commentZip(String fileName,String filePath) {
	 	File file = new File(fileName);
	 	if(null!=file.getName()&&!"".equals(file.getName())){
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();
        }  
        //保存  
        try {  
            FileCopyUtils.copy(file, new File(filePath+"/"+fileName.substring(fileName.lastIndexOf('\\') + 1)));
        } catch (Exception e) {
        	log.info(e);
	 	}
    }
	}
    @SuppressWarnings("rawtypes")
	public static void zipToFile(String fileName,String xmlPath){
    	try {
		 String toDisk = xmlPath;//"F://projectFile//";//toFolder;//接收解压后的存放路径
		 ZipFile zfile = new ZipFile(fileName,"utf-8");//连接待解压文件
		 Enumeration zList = zfile.getEntries();//得到zip包里的所有元素
		 ZipEntry ze;
		 byte[] buf = new byte[1024];
		 while (zList.hasMoreElements()) {
			 ze = (ZipEntry) zList.nextElement();
			 if (ze.isDirectory()) {
				 log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped...");
				 continue;
			 }
			 OutputStream outputStream;
			 InputStream inputStream;
				 //以ZipEntry为参数得到一个InputStream，并写到OutputStream中
				 outputStream = new BufferedOutputStream(
						 new FileOutputStream(getRealFileName(toDisk, ze.getName())));
				 inputStream = new BufferedInputStream(zfile.getInputStream(ze));
				 int readLen;
				 while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
					 outputStream.write(buf, 0, readLen);
				 }
				 inputStream.close();
				 outputStream.close();
			 }
		 zfile.close();
			
		} catch (Exception e) {
			log.info(e);
		}
	 }
 
	 /**
	  * 用于保存多媒体文件工具
	  * @param file
	  * @return
	  * @throws Exception
	  */
	public static List<MultiMedia> generateMultiMedia(File file)
	{
		List<MultiMedia> listMultiMedia = new ArrayList<>();
		try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        FileInputStream is = new FileInputStream(file);
        Document document = db.parse(is);
        NodeList list = document.getElementsByTagName("figure");
        for (int i = 0; i < list.getLength(); ++i)
        {
        	MultiMedia media = new MultiMedia();
            Element element = (Element) list.item(i);
            String title = null!=element.getElementsByTagName(TITLE2)&&element.getElementsByTagName(TITLE2).item(0)!=null?element.getElementsByTagName(TITLE2).item(0).getTextContent():"";
            String code = null!=element.getElementsByTagName(GRAPHIC)&&element.getElementsByTagName(TITLE2).item(0)!=null&&element.getElementsByTagName(TITLE2).item(0).getAttributes().getNamedItem(INFO_ENTITY_IDENT)!=null?element.getElementsByTagName(TITLE2).item(0).getAttributes().getNamedItem(INFO_ENTITY_IDENT).getNodeValue():"";
            String dmCode = file.getName().substring(0,file.getName().lastIndexOf('.'));
            media.setCode(code);
            media.setDmCode(dmCode);
            media.setTitle(title);
            listMultiMedia.add(media);
        }
        is.close();
    	
		} catch (Exception e) {
			log.info(e);
		}
		return listMultiMedia;
	}
	/**
	 * zip包名截取
	 * @param name
	 * @return
	 */
    public static String zipNameSubString(String name1) {   
    	String folderName="";
    	String name=name1;
   	 	if(name!=null&&name!=""){
   			int pos1 = name.lastIndexOf('\\');
   			if (pos1 != -1)  {
   				name=name.substring(pos1 + 1);
   			}
   	 		int winSep = name.lastIndexOf('.');
   	 		//截取压缩包的文件名生成文件夹
   	 		folderName=name.substring(0, winSep);
   	 	}
        return folderName;   
    } 
    /**
     * 从图片路径中截取图片文件名
     * @param name
     * @return
     */
    public static String fileNameSubString(String name) {   
    	String imageName="";
		int pos2 = name.lastIndexOf('\\');
		if (pos2 != -1)  {
			imageName=name.substring(pos2 + 1);
		}
        return imageName;   
    } 
	 /**

	  * 给定根目录，返回一个相对路径所对应的实际文件名.

	  * @param zippath 指定根目录

	  * @param absFileName 相对路径名，来自于ZipEntry中的name

	  * @return java.io.File 实际的文件

	  */
	 public static File getRealFileName(String zippath, String absFileName){
		 log.info("文件名："+absFileName);
		 String[] dirs = absFileName.split("/" , absFileName.length());
		 File ret = new File(zippath);// 创建文件对象
		 if (dirs.length > 1) {
			 for (int i = 0; i < dirs.length - 1; i++) {
				 ret = new File(ret, dirs[i]);
			 }
		 }
		 if (!ret.exists()) {// 检测文件是否存在
			 ret.mkdirs();// 创建此抽象路径名指定的目录
		 }
		 ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
		 return ret;
	 }
	 /**
	  * 获取文件的扩展名
	  */
	 public static String getExtensionName(String filename) {   
	        if ((filename != null) && (filename.length() > 0)) {   
	            int dot = filename.lastIndexOf('.');   
	            if ((dot >-1) && (dot < (filename.length() - 1))) {   
	                return filename.substring(dot + 1);   
	            }   
	        }   
	        return filename;   
	    }
	public static void updateMedias(File file, List<MultiMedia> medias,MultiMediaRepository multiMediaRepository){
		try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        FileInputStream is = new FileInputStream(file);
        Document document = db.parse(is);
        NodeList list = document.getElementsByTagName("figure");
        for (int i = 0; i < list.getLength(); ++i)
        {
        	
            Element element = (Element) list.item(i);
            String title = null!=element.getElementsByTagName(TITLE2)&&element.getElementsByTagName(TITLE2).item(0)!=null?element.getElementsByTagName(TITLE2).item(0).getTextContent():"";
            String code = null!=element.getElementsByTagName(GRAPHIC)&&element.getElementsByTagName(GRAPHIC).item(0)!=null&&element.getElementsByTagName(GRAPHIC).item(0).getAttributes().getNamedItem(INFO_ENTITY_IDENT)!=null?element.getElementsByTagName(GRAPHIC).item(0).getAttributes().getNamedItem(INFO_ENTITY_IDENT).getNodeValue():"";
            String dmCode = file.getName().substring(0,file.getName().lastIndexOf('.'));
            MultiMedia media=getMedia(code, medias);
            if(media!=null) {
        	  media=multiMediaRepository.findOne(media.getId());
  	        	media.setDmCode(dmCode);
  	            media.setTitle(title);
  	            multiMediaRepository.save(media);	
            }
          
           
        }
        is.close();
    	
		} catch (Exception e) {
			log.info(e);
		}
	} 	
	
	public static MultiMedia getMedia(String code,List<MultiMedia> medias) {
		for (MultiMedia media : medias) {
			if(media.getCode().equals(code))
				return media;
		}
		return null;
	}
	
	
}